package config

import (
	"fmt"
	"os"
	"strconv"

	"gopkg.in/yaml.v2"
)

// LoadConfig 从文件加载配置
func LoadConfig(filename string) (*Config, error) {
	data, err := os.ReadFile(filename)
	if err != nil {
		return nil, fmt.Errorf("read config file failed: %v", err)
	}

	var config Config
	if err := yaml.Unmarshal(data, &config); err != nil {
		return nil, fmt.Errorf("parse config file failed: %v", err)
	}

	// 从环境变量加载配置
	if err := loadEnvConfig(&config); err != nil {
		return nil, fmt.Errorf("load env config failed: %v", err)
	}

	// 验证配置
	if err := config.Validate(); err != nil {
		return nil, fmt.Errorf("validate config failed: %v", err)
	}

	return &config, nil
}

// loadEnvConfig 从环境变量加载配置
func loadEnvConfig(cfg *Config) error {
	// 数据库配置
	if host := os.Getenv("DB_HOST"); host != "" {
		cfg.Database.Host = host
	}
	if port := os.Getenv("DB_PORT"); port != "" {
		if p, err := strconv.Atoi(port); err == nil {
			cfg.Database.Port = p
		}
	}
	if user := os.Getenv("DB_USER"); user != "" {
		cfg.Database.User = user
	}
	if password := os.Getenv("DB_PASSWORD"); password != "" {
		cfg.Database.Password = password
	}
	if dbname := os.Getenv("DB_NAME"); dbname != "" {
		cfg.Database.DBName = dbname
	}

	return nil
}

// Config 主配置结构
type Config struct {
	OKEx     OKExConfig     `yaml:"okex"`
	Market   MarketConfig   `yaml:"market"`
	Database DatabaseConfig `yaml:"database"`
	Alert    AlertConfig    `yaml:"alert"`
}

// Validate 验证配置
func (c Config) Validate() error {
	// 验证数据库配置
	if err := c.Database.Validate(); err != nil {
		return fmt.Errorf("database config: %v", err)
	}

	// 验证市场配置
	if err := c.Market.Validate(); err != nil {
		return fmt.Errorf("market config: %v", err)
	}

	// 验证告警配置
	if len(c.Alert.Channels) == 0 {
		return fmt.Errorf("no alert channels configured")
	}

	return nil
}
